package cn.buttheway.moodmusicdiary.utils;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.mlkit.nl.languageid.LanguageIdentification;
import com.google.mlkit.nl.languageid.LanguageIdentifier;
import com.google.mlkit.nl.sentiment.Sentiment;
import com.google.mlkit.nl.sentiment.SentimentAnalyzer;
import com.google.mlkit.nl.sentiment.SentimentAnalyzerOptions;

public class MLKitHelper {

    private SentimentAnalyzer sentimentAnalyzer;
    private LanguageIdentifier languageIdentifier;

    public MLKitHelper() {
        languageIdentifier = LanguageIdentification.getClient();
        // 默认使用英语分析器，我们会在分析前检测语言
        sentimentAnalyzer = SentimentAnalyzer.create(new SentimentAnalyzerOptions.Builder().build());
    }

    public void analyzeSentiment(final String text, final OnSuccessListener<String> successListener, final OnFailureListener failureListener) {
        languageIdentifier.identifyLanguage(text)
                .addOnSuccessListener(new OnSuccessListener<String>() {
                    @Override
                    public void onSuccess(String languageCode) {
                        // 根据检测到的语言选择合适的情感分析器
                        SentimentAnalyzerOptions options;
                        if ("zh".equals(languageCode)) {
                            options = new SentimentAnalyzerOptions.Builder().setLanguageCode("zh").build();
                        } else {
                            // 默认使用英语
                            options = new SentimentAnalyzerOptions.Builder().setLanguageCode("en").build();
                        }
                        sentimentAnalyzer = SentimentAnalyzer.create(options);

                        // 进行情感分析
                        sentimentAnalyzer.analyzeSentiment(text)
                                .addOnSuccessListener(new OnSuccessListener<Sentiment>() {
                                    @Override
                                    public void onSuccess(Sentiment sentiment) {
                                        String result;
                                        if (sentiment.getSentiment() > 0) {
                                            result = "积极";
                                        } else if (sentiment.getSentiment() < 0) {
                                            result = "消极";
                                        } else {
                                            result = "中性";
                                        }
                                        successListener.onSuccess(result);
                                    }
                                })
                                .addOnFailureListener(failureListener);
                    }
                })
                .addOnFailureListener(failureListener);
    }
}